package com.syyo.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.syyo.common.domain.ResultVo;
import com.syyo.common.utils.MyJSONUtils;
import com.syyo.common.utils.MyListUtils;
import com.syyo.gulimall.cart.feign.ProductFeign;
import com.syyo.gulimall.cart.interceptor.CartInterceptor;
import com.syyo.gulimall.cart.service.CartService;
import com.syyo.gulimall.cart.vo.Cart;
import com.syyo.gulimall.cart.vo.CartItem;
import com.syyo.gulimall.cart.vo.SkuInfoVo;
import com.syyo.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @ author: wang
 * @ date: 2021/4/20 16:03
 * @ Description:
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {

    private final String CART_PREFIX = "gulimall:cart:";// redis的购物车前缀

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeign productFeign;

    @Autowired
    ThreadPoolExecutor executor;

    /**
     * 添加购物车
     *
     * @param skuId
     * @param num
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public CartItem add(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        // 判断是用临时购物车还是用户购物车
        BoundHashOperations<String, Object, Object> cartRedis = getCartRedis();

        String res = (String) cartRedis.get(skuId.toString());

        if (StringUtils.isEmpty(res)) {
            // 说明购物没有商品
            // 商品添加到购物车
            CartItem cartItem = new CartItem();
            // 1.远程调用查询商品信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                ResultVo skuInfo = productFeign.getSkuInfo(skuId);
                SkuInfoVo skuInfoVo = MyJSONUtils.typeCast(new TypeReference<SkuInfoVo>() {
                }, skuInfo.getData());
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfoVo.getSkuDefaultImg());
                cartItem.setTitle(skuInfoVo.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(skuInfoVo.getPrice());
            }, executor);


            // 2.远程查询组合信息,runAsync=不关心返回值
            CompletableFuture<Void> getSkuSaleAttrTask = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeign.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrTask).get();

            String jsonString = JSON.toJSONString(cartItem);

            cartRedis.put(skuId.toString(), jsonString);
            return cartItem;
        } else {
            // 购物车有这个商品，就数量递增
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            String jsonString = JSON.toJSONString(cartItem);
            cartRedis.put(skuId.toString(), jsonString);
            return cartItem;
        }
    }

    /**
     * 根据skuId查询购物的商品
     *
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {

        // 判断是用临时购物车还是用户购物车
        BoundHashOperations<String, Object, Object> cartRedis = getCartRedis();
        String res = (String) cartRedis.get(skuId.toString());
        return JSON.parseObject(res, CartItem.class);
    }


    /**
     * 查询整个购物车
     *
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            // 登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();

            // 先判断临时购物车有没有数据,如果有就做合并操作
            List<CartItem> tempCartItems = getCartItems(cartKey);
            if (MyListUtils.isNotEmpty(tempCartItems)) {
                // 合并处理
                for (CartItem tempCartItem : tempCartItems) {
                    add(tempCartItem.getSkuId(), tempCartItem.getCount());
                }
                //  清空购物车
                clearCart(cartKey);
            }
            // 获取合并后的购物车数据
            cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        } else {
            // 没登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            // 获取临时购物车的数据
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    @Override
    public void itemCheck(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartRedis = getCartRedis();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1 ? true : false);
        String jsonString = JSON.toJSONString(cartItem);
        cartRedis.put(cartItem.getSkuId().toString(), jsonString);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartRedis = getCartRedis();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String jsonString = JSON.toJSONString(cartItem);
        cartRedis.put(cartItem.getSkuId().toString(), jsonString);

    }

    @Override
    public void delItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartRedis = getCartRedis();
        cartRedis.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCurrentUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;

        } else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            for (CartItem cartItem : cartItems) {
                if (cartItem.getCheck()) {
                    // 获取sku的价格
                    BigDecimal price = productFeign.getPrice(cartItem.getSkuId());
                    cartItem.setPrice(price);
                }
            }
            return cartItems;


//            return cartItems.stream().filter(item -> item.getCheck())
//                    .map(item->{
//                        // 更新最新价格
//                        BigDecimal price = productFeign.getPrice(item.getSkuId());
//                        item.setPrice(price);
//                        return item;
//                    })
//                    .collect(Collectors.toList());

        }


    }

    /**
     * 根据redisKey查询购物车信息
     *
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> redisHash = redisTemplate.boundHashOps(cartKey);
        List<Object> values = redisHash.values();
        if (MyListUtils.isNotEmpty(values)) {
            List<CartItem> collect = values.stream().map(obj -> {
                String str = (String) obj;
                return JSON.parseObject(str, CartItem.class);
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 获取购物车的redis，临时redisKey 或者 在线redisKey
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartRedis() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        String cartKey = "";

        if (userInfoTo.getUserId() != null) {
            // 用户登录了
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            // 用户没有登录
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        // 绑定key
        return redisTemplate.boundHashOps(cartKey);
    }

    /**
     * 清空购物车
     *
     * @param cartKey
     * @return
     */
    private void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }
}
